package com.ahwei.web.filter;


import com.ahwei.util.LogUtils;
import com.ahwei.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author：ahwei163@qq.com
 *
 * @date: 202*-03-05 18:43:38
 * @description: 防盗链过滤器！
 */
@WebFilter(filterName = "AntiStealingLinkFilter" ,urlPatterns = "")
public class AntiStealingLinkFilter implements Filter {
    public static String url = null;
    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;

        servletRequest.setCharacterEncoding("UTF-8");
        //第一次进来url为空
        if (StringUtils.isEmpty(url)){
            //获取请求url
            String requestURL = request.getRequestURL().toString();
            String servletPath = request.getServletPath();
            //将servletPath替换为空
            url = requestURL.replace(servletPath,"");
        }
        String referer = request.getHeader("referer");

        //用来打印请求路径
        LogUtils.info("URL = " + request.getRequestURL());
        //检测是否以指定前缀开始
        if (referer != null && !referer.startsWith(url)) {
            request.getRequestDispatcher("/img/steal.png").forward(servletRequest, servletResponse);
            return;
        }

        //servletResponse.setContentType("text/html;charset=utf-8");
        chain.doFilter(servletRequest, servletResponse);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
